package com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_zhijian.R;
import com.xiaoxing.zhinenghuacangku_zhijian.R2;
import com.xiaoxing.zhinenghuacangku_zhijian.di.component.DaggerChouJianTuiKuLieBiaoComponent;
import com.xiaoxing.zhinenghuacangku_zhijian.di.module.ChouJianTuiKuLieBiaoModule;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.contract.ChouJianTuiKuLieBiaoContract;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.presenter.ChouJianTuiKuLieBiaoPresenter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.adapter.ChouJianTuiKuLieBiaoAdapter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.ChouJianChuKuLieBiao;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.ChouJianTuiKuLieBiao;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.GetUserSpaceList;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ButtonUtils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_ZHI_JIAN_ACTIVITY_CHOU_JIAN_TUI_KU_LIE_BIAO)
public class ChouJianTuiKuLieBiaoActivity extends BaseActivity<ChouJianTuiKuLieBiaoPresenter> implements ChouJianTuiKuLieBiaoContract.View, OnRefreshListener, ChouJianTuiKuLieBiaoAdapter.IChouJianTuiKuLieBiaoAdapter {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private ChouJianTuiKuLieBiaoAdapter mAdapter;
    private List<ChouJianChuKuLieBiao> mDataBeanList = new ArrayList<>();
    private AlertDialog mAlertDialog;
    private String mSelectedBufferId;
    private String mSelectedBufferName;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerChouJianTuiKuLieBiaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .chouJianTuiKuLieBiaoModule(new ChouJianTuiKuLieBiaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_chou_jian_tui_ku_lie_biao; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_chou_jian_tui_ku_lie_biao));

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        //getChouJianTuiKuLieBiaoList();
        simpleOutStoreBackListForCgy();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(ChouJianTuiKuLieBiaoActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new ChouJianTuiKuLieBiaoAdapter(ChouJianTuiKuLieBiaoActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#D8D8D8"));
        empty_text.setText("暂无数据");
    }

    /**
     * @param
     * @return
     * @method
     * @description 仓管员 抽检退库 列表
     * @date: 2020/9/15 0015 11:40
     * @author: 小星
     */
    private void simpleOutStoreBackListForCgy() {

        showLoading();
        String methodNames = "SimpleOutStoreBackListForCgy";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));

        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<ChouJianChuKuLieBiao> chouJianChuKuLieBiaos = ArmsUtils.parseString2List(result, ChouJianChuKuLieBiao.class);

                        if (chouJianChuKuLieBiaos != null && chouJianChuKuLieBiaos.size() > 0) {
                            mDataBeanList.clear();
                            mDataBeanList.addAll(chouJianChuKuLieBiaos);
                            mAdapter.notifyDataSetChanged();
                            mEmptyLayout.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyLayout.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        }
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        //getChouJianTuiKuLieBiaoList();
        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void getChouJianTuiKuLieBiaoDataSuccess(ChouJianTuiKuLieBiao entityList) {

//        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
//            mDataBeanList.clear();
//            mDataBeanList.addAll(entityList.getData());
//            mAdapter.notifyDataSetChanged();
//            mEmptyLayout.setVisibility(View.GONE);
//            mRecyclerView.setVisibility(View.VISIBLE);
//        } else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//        }

    }

    private void getChouJianTuiKuLieBiaoList() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getChouJianTuiKuLieBiaoList(map);
    }

    @Override
    public void tuiHui(ChouJianChuKuLieBiao item) {

        if (item.getIsauto().equals("1")) {
            getSimpleStorageSpname(item);
        } else if (item.getIsauto().equals("0")) {
            getSimpleStorageSpname(item);
        }
    }

    /**
     * @param
     * @return
     * @method
     * @description 点击"退回"按钮
     * 如果isauto=1  调用
     * <p>
     * 弹出窗体  调用 public string GetSimpleStorageSpname(string uid)
     * @date: 2020/9/15 0015 11:52
     * @author: 小星
     */
    private void getSimpleStorageSpname(ChouJianChuKuLieBiao item) {

        showLoading();
        String methodNames = "GetSimpleStorageSpname";


        SoapParams paramss = null;
        paramss = new SoapParams();

        if (item.getIsauto().equals("1")) {
            methodNames = "GetSimpleStorageSpname";
            paramss.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));

        } else if (item.getIsauto().equals("0")) {
            methodNames = "GetUserSpaceList";
            paramss.put("spname", "");
            paramss.put("user_id", mSharedPreferencesHelper.getString(BaseConstants.UID));

        }


        String finalMethodNames = methodNames;
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(finalMethodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        showKuWei(result, item);
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    private void showKuWei(String result, ChouJianChuKuLieBiao item) {


        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_zhi_jian_layout_qu_yang_qu, null);
        NiceSpinner niceSpinner = myView.findViewById(R.id.nice_position);
        List<GetUserSpaceList> getSimpleZoneBuffers = new Gson().fromJson(result, new TypeToken<List<GetUserSpaceList>>() {
        }.getType());

        if (getSimpleZoneBuffers != null && getSimpleZoneBuffers.size() > 0) {
            initSpPosition(getSimpleZoneBuffers, niceSpinner);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择库位");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {
                    peopleOutStoreBackForQuality(item);
                    mAlertDialog.dismiss();
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    private void initSpPosition(List<GetUserSpaceList> getSimpleZoneBuffers, NiceSpinner spPosition) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getSimpleZoneBuffers.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getSimpleZoneBuffers.get(i).getSpname())
            ));
        }
        mSelectedBufferId = String.valueOf(getSimpleZoneBuffers.get(0).getSpid());
        mSelectedBufferName = getSimpleZoneBuffers.get(0).getSpname();
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedBufferId = String.valueOf(getSimpleZoneBuffers.get(position).getSpid());
                mSelectedBufferName = getSimpleZoneBuffers.get(position).getSpname();
            }
        });
    }

    /**
     * @param
     * @return
     * @method
     * @description 选择库位后 调用
     * @date: 2020/9/15 0015 12:00
     * @author: 小星
     */
    private void peopleOutStoreBackForQuality(ChouJianChuKuLieBiao item) {

        showLoading();
        String methodNames = "PeopleOutStoreBackForQuality";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("mid", item.getMid());
        paramss.put("spname", item.getSpname());
        paramss.put("spid", mSelectedBufferId);
        paramss.put("buffername", mSelectedBufferName);
        paramss.put("monthid", item.getMonthid());
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        showMessage("命令发送成功");
                        simpleOutStoreBackListForCgy();
                    } else {
                        showMessage("命令发送失败");

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

}
